package com.netdimensions.confluence.plugins;

import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import java.util.AbstractList;
import java.util.List;

/**
 * Created by IntelliJ IDEA.
 * User: Rob
 * Date: 1/17/11
 * Time: 9:55 PM
 * To change this template use File | Settings | File Templates.
 */
public final class XPathUtils {
    // Suppress default constructor for noninstantiability
    private XPathUtils() {
        throw new AssertionError();
    }

    public static final String string(final String expression, final Node item) {
        try {
            return newXPath().evaluate(expression, item);
        } catch (final XPathExpressionException e) {
            throw new RuntimeException(e);
        }
    }

    public static final List<Node> nodes(final String expression, final Element item) {
        try {
            return asList((NodeList) newXPath().evaluate(expression, item, XPathConstants.NODESET));
        } catch (final XPathExpressionException e) {
            throw new RuntimeException(e);
        }
    }

    private static final XPath newXPath() {
        return XPathFactory.newInstance().newXPath();
    }

    private static final List<Node> asList(final NodeList nodeList) {
        return new AbstractList<Node>() {
            @Override
            public final Node get(final int index) {
                if (index >= 0 && index < nodeList.getLength()) {
                    return nodeList.item(index);
                } else {
                    throw new IndexOutOfBoundsException();
                }
            }

            @Override
            public final int size() {
                return nodeList.getLength();
            }
        };
    }
}
